/**
 * 格式化日期
 * @param value 传入的日期值
 * @param format 格式
 * @returns 格式化后的字符串
 */
const formatDate = (value: any, format: string = 'yyyy-MM-dd HH:mm:ss') => {
  if (!value) return '';
  try {
    const date = new Date(value)
    const config = {
      yyyy: date.getFullYear(),
      M: date.getMonth() + 1,
      MM: formatNumber(date.getMonth() + 1),
      W: date.getDay(),
      WW: formatNumber(date.getDay()),
      d: date.getDate(),
      dd: formatNumber(date.getDate()),
      H: date.getHours(),
      HH: formatNumber(date.getHours()),
      h: date.getHours() > 12 ? (date.getHours() - 12) : date.getHours(),
      hh: formatNumber(date.getHours()) > 12 ? (formatNumber(date.getHours()) - 12) : formatNumber(date.getHours()),
      m: date.getMinutes(),
      mm: formatNumber(date.getMinutes()),
      s: date.getSeconds(),
      ss: formatNumber(date.getSeconds()),
      A: date.getHours() < 12 ? 'AM' : 'PM',
      a: date.getHours() < 12 ? 'am' : 'pm'
    }

    const formatConfigs = format.match(/[a-zA-Z]+/g)
    formatConfigs.forEach(item => {
      format = format.replace(item, config[item])
    })
    return format
  } catch (ex) {
    return value
  }
}

const formatNumber = (num) => {
  return num < 10 ? `0${num}` : num
}

export {
  formatDate
}